//
//  UIView+Extension.swift
//  Backhome
//
//  Created by vbn on 2018/7/12.
//  Copyright © 2018年 SmartHome. All rights reserved.
//

import Foundation


extension UIView {
    
    @IBInspectable
    public var KNCornerRadius: CGFloat {
        get { return self.layer.cornerRadius}
        set {
            self.layer.cornerRadius = newValue
            self.layer.masksToBounds = newValue>0
        }
    }
    
    @IBInspectable
    public var KNBorderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    public var KNBorderColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!)
            return color
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
    
    @IBInspectable
    public var KNShadowRadius: CGFloat {
        get {
            return layer.shadowRadius
        }
        set {
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 0, height: 2)
            layer.shadowOpacity = 0.4
            layer.shadowRadius = KNShadowRadius
        }
    }
    
    public class func KNFromNib<T: UIView>() ->T? {
        
        guard let v = Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)?.first else {
            return nil
        }
        print("\(String(describing: T.self))")
        return v as? T
        
    }
    
    public func KNDrawDottedLine(start p0: CGPoint, end p1: CGPoint, tag: Int, lineColor: UIColor) {
        var shapeLayer: CAShapeLayer? = self.layer.sublayers?.filter({$0.name == String(tag) }).first as? CAShapeLayer
        if shapeLayer == nil{
            shapeLayer = CAShapeLayer()
            shapeLayer!.name = String(tag)
            self.layer.addSublayer(shapeLayer!)
        }
        self.KNDrawDottedLine(start: p0, end: p1, layer: shapeLayer!, lineColor: lineColor)
        
    }
    
    public func KNDrawDottedLine(start p0: CGPoint, end p1: CGPoint, layer: CAShapeLayer, lineColor: UIColor) {
        
        layer.strokeColor = lineColor.cgColor
        layer.lineWidth = 1
        layer.lineDashPattern = [3, 3] // 7 is the length of dash, 3 is length of the gap.
        let path = CGMutablePath()
        path.addLines(between: [p0, p1])
        layer.path = path
    }
    
    public func KNRoundCorners(_ corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}
